package cn.monkey.family.server.domain.shop.item.type;

import cn.monkey.family.data.crud.repository.QueryDslQueryRequestRepository;
import cn.monkey.family.data.dict.DictRepository;
import cn.monkey.family.data.shop.item.type.ItemType;
import cn.monkey.family.data.shop.item.type.ItemTypeQueryRequest;
import cn.monkey.family.data.shop.item.type.QItemType;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface ItemTypeRepository extends QueryDslQueryRequestRepository<ItemType, String, ItemTypeQueryRequest>, DictRepository<ItemType> {
    @Override
    default Predicate queryDslPredicate(ItemTypeQueryRequest queryRequest) {
        QItemType qItemType = QItemType.itemType;
        BooleanExpression expression = qItemType.module.eq(ItemType.MODULE);

        List<String> key = queryRequest.getKey();
        if (!CollectionUtils.isEmpty(key)) {
            expression = expression.and(qItemType.key.in(key));
        }
        List<String> parentKey = queryRequest.getParentKey();
        if (!CollectionUtils.isEmpty(parentKey)) {
            expression = expression.and(qItemType.parentKey.in(parentKey));
        }
        return expression;
    }

    @Override
    default List<ItemType> selectAll(Sort sort) {
        ItemTypeQueryRequest queryRequest = ItemTypeQueryRequest.builder().build();
        return this.findAll(this.queryDslPredicate(queryRequest), sort);
    }

    @Override
    default Optional<ItemType> selectByKey(String key) {
        return this.findOne(this.queryDslPredicate(ItemTypeQueryRequest.builder().key(List.of(key)).build()));
    }
}
